#pragma once

#include <string>
#include <vector>
#include <memory>
#include <map>
#include "viml/instruction.h"
#include "viml/lexer.h"
#include "viml/parser.h"
#include "viml/ast.h"
#include "viml/function.h"
#include "viml/scope_manager.h"
#include "viml/simple_optimizer.h"
#include "viml/optimization_pipeline.h"

namespace viml {

// 编译器前端，负责将VimL源代码编译为字节码
class Compiler : public ASTVisitor {
private:
    std::vector<Instruction> instructions;
    std::vector<Value> constants;
    std::vector<std::string> names;
    std::vector<int> instruction_lines;  // 存储每条指令对应的行号

    // 函数表
    std::vector<std::shared_ptr<Function>> functions;

    // 优化器
    std::unique_ptr<SimpleOptimizer> optimizer_;
    
    // 优化管道（可选，用于更灵活的优化配置）
    std::unique_ptr<OptimizationPipeline> pipeline_;

    // 代码生成上下文
    struct CompileContext {
        std::map<std::string, uint8_t> local_variables;
        uint8_t next_register;
        bool in_function; // 标记是否在函数内部

        CompileContext() : next_register(0), in_function(false) {}
    };

    CompileContext context;
    size_t current_line = 0;  // 当前编译行号
    
    // 辅助方法
    uint8_t allocate_register();
    uint16_t add_constant(const Value& value);
    uint16_t add_name(const std::string& name);
    void emit(OpCode op, uint8_t a = 0, uint8_t b = 0, uint8_t c = 0);
    void emit_abx(OpCode op, uint8_t a, uint16_t bx);
    uint8_t get_or_create_local(const std::string& name);
    
    // 作用域相关
    void emit_scope_load(uint8_t reg, ScopeId scope, uint16_t name_idx);
    void emit_scope_store(ScopeId scope, uint16_t name_idx, uint8_t value_reg);
    std::pair<ScopeId, std::string> parse_variable_scope(const std::string& name);
    
public:
    Compiler();
    
    // 编译源代码
    std::shared_ptr<Bytecode> compile(const std::string& source, const std::string& filename = "<input>");
    
    // 访问者模式实现
    void visit(NumberLiteral& node) override;
    void visit(StringLiteral& node) override;
    void visit(Identifier& node) override;
    void visit(SpecialConstantNode& node) override;
    void visit(BinaryExpression& node) override;
    void visit(UnaryExpression& node) override;
    void visit(CallExpression& node) override;
    void visit(ListLiteral& node) override;
    void visit(DictLiteral& node) override;
    void visit(IndexExpression& node) override;
    void visit(LetStatement& node) override;
    void visit(EchoStatement& node) override;
    void visit(IfStatement& node) override;
    void visit(WhileStatement& node) override;
    void visit(ForStatement& node) override;
    void visit(FunctionStatement& node) override;
    void visit(ReturnStatement& node) override;
    void visit(CallStatement& node) override;
    void visit(Program& node) override;
    
    // 获取编译结果
    const std::vector<Instruction>& get_instructions() const { return instructions; }
    const std::vector<Value>& get_constants() const { return constants; }
    const std::vector<std::string>& get_names() const { return names; }
    const std::vector<std::shared_ptr<Function>>& get_functions() const { return functions; }
    
    // 重置编译器状态
    void reset();

    // 优化器控制
    void enable_optimizations();
    void disable_optimizations();
    SimpleOptimizer::OptimizationSummary get_optimization_summary() const;
    
    // 优化管道访问
    OptimizationPipeline* get_optimization_pipeline() { return pipeline_.get(); }
    const OptimizationPipeline* get_optimization_pipeline() const { return pipeline_.get(); }
};

} // namespace viml